package com.yc.hotel.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 邮件发送工具类
 * @author navy
 * Company 源辰信息
 * @date 2022年6月23日
 * Email haijunzhou@hnit.edu.cn
 */
@Component
public class SendEmailUtil {
	@Value("${spring.mail.username}")
	private String sendEmail; // 发件箱
	
	@Autowired
	private JavaMailSender sender;
	
	public void setSendEmail(String sendEmail) {
		this.sendEmail = sendEmail;
	}
	
	/**
	 * 邮件发送方法
	 * @param receiveEmail
	 * @param code
	 * @param nickName
	 * @return
	 */
	public boolean sendEmail(String receiveEmail, String code, String nickName) {
		if(StringUtil.checkNull(receiveEmail, code, nickName)) {
			return false;
		}
		try {
			MimeMessage mailMessage = sender.createMimeMessage();
			
			MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
			messageHelper.setTo(receiveEmail);
			messageHelper.setFrom(sendEmail);
			messageHelper.setSubject("city night注册中心");
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE");
			String str = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>尊敬的："+nickName+"，您好！</p>"
					+ "<p style='text-indent:2em; font-size: 20px;'>city night，您本次的注册码是 "
					+ "<span style='font-size:30px;font-weight:bold;color:red'>"+code+"</span>，3分钟之内有效，请尽快使用！</p>"
					+ "<p style='text-align:right; padding-right: 20px;'>"
					+ "<span style='font-size:18px; float:right; margin-right: 20px;'>"+sdf.format(new Date())+"</span></body></html>";
			
			messageHelper.setText(str, true);
			
			sender.send(mailMessage);
			
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return false;
	}
}
